package ru.ifmo.itmokis.sim;

import ru.ifmo.itmokis.util.Config;
import java.util.ArrayList;
import java.util.List;
import ru.ifmo.itmokis.domain.Time;

/**
 *
 * @author Ivan Stepuk
 */
public final class Clock implements Runnable {

    private Config config;
    // ^ Dependencies ^
    private Thread thread = new Thread(null, this, "clock");
    private List<ClockListener> listeners = new ArrayList<ClockListener>();
    private Time currentTime = Time.ZERO;
    private boolean running = false;

    public Clock(Config config) {
        this.config = config;
    }

    public Time getCurrentTime() {
        return currentTime;
    }

    public void addClockListener(ClockListener listener) {
        listeners.add(listener);
    }

    public void removeClockListener(ClockListener listener) {
        listeners.remove(listener);
    }

    public void play() {
        if (!thread.isAlive()) {
            thread.start();
        }
        running = true;
    }

    public void pause() {
        running = false;
    }

    public void stop() {
        pause();
        thread.interrupt();
        thread = new Thread(null, this, "clock");
        currentTime = Time.ZERO;
    }

    @Override
    public void run() {
        loop:
        while (true) {
            for (ClockListener listener : listeners) {
                listener.process(currentTime);
            }
            do {
                try {
                    Thread.sleep(config.getInt("Period"));
                } catch (InterruptedException ex) {
                    break loop;
                }
            } while (!running);
            currentTime = currentTime.add(Time.ONE_HOUR);
        }
    }
}
